package com.seqb.manage.file.controller;

import com.github.pagehelper.Page;
import com.seqb.annotation.Log;
import com.seqb.common.FileType;
import com.seqb.common.Query;
import com.seqb.common.ResultVo;
import com.seqb.common.config.SeqbConfig;
import com.seqb.common.controller.BaseController;
import com.seqb.manage.file.domain.FileDO;
import com.seqb.manage.file.service.FileService;
import com.seqb.utils.FileUtils;
import com.seqb.utils.PageUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lilinshen
 * @title 文件管理表
 * @description 请填写相关描述
 * @date 2019/11/15
 */
@Controller
@RequestMapping("/manage/file/file")
public class FileController extends BaseController {
    @Autowired
    private FileService fileService;
    @Autowired
    private SeqbConfig seqbConfig;

    @GetMapping()
    @RequiresPermissions("manage:file:file:list")
    @Log("文件管理表列表")
    String file(Model model, HttpServletRequest request) {
        String prefix = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        model.addAttribute("prefix", prefix);
        return "manage/file/file.list";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("manage:file:file:list")
    @Log("文件管理表列表")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        Page<FileDO> page = fileService.list(query);
        PageUtils pageUtils = new PageUtils(page.getResult(), page.getTotal());
        return pageUtils;
    }

    @GetMapping("/add")
    @RequiresPermissions("manage:file:file:add")
    @Log("文件管理表添加")
    String add() {
        return "manage/file/file.add";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("manage:file:file:edit")
    @Log("文件管理表编辑")
    String edit(@PathVariable("id") Long id, Model model) {
        FileDO file = fileService.get(id);
        model.addAttribute("file", file);
        return "manage/file/file.edit";
    }

    /**
     * 添加保存
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("manage:file:file:add")
    @Log("文件管理表添加保存")
    public ResultVo save(FileDO file) {
        if (fileService.save(file) > 0) {
            return ResultVo.ok();
        }
        return ResultVo.error();
    }

    /**
     * 编辑保存
     */
    @ResponseBody
    @RequestMapping("/update")
    @Log("文件管理表编辑保存")
    @RequiresPermissions("manage:file:file:edit")
    public ResultVo update(FileDO file) {
        fileService.update(file);
        return ResultVo.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("manage:file:file:remove")
    @Log("文件管理表删除")
    public ResultVo remove(Long id) {
        if (fileService.remove(id) > 0) {
            return ResultVo.ok();
        }
        return ResultVo.error();
    }

    /**
     * 批量删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("manage:file:file:batchRemove")
    @Log("文件管理表批量删除")
    public ResultVo remove(@RequestParam("ids[]") Long[] ids) {
        fileService.batchRemove(ids);
        return ResultVo.ok();
    }

    /**
     * 上传文件
     */
    @ResponseBody
    @PostMapping("/upload")
    public ResultVo upload(@RequestParam("file") MultipartFile file, Long domainId, String domainName, String domainField) {
        try {
            String originalFilename = file.getOriginalFilename();
            String oldFileName = originalFilename.substring(originalFilename.lastIndexOf("\\") + 1);
            String newFileName = FileUtils.renameToUuid(oldFileName);
            String fileUrl = "/files/" + FileUtils.generatePath() + newFileName;
            FileDO sysFile = new FileDO(FileType.fileType(oldFileName), fileUrl, oldFileName, file.getSize(), domainId, domainName, domainField);
            FileUtils.uploadFile(file.getBytes(), seqbConfig.getUploadPath() + FileUtils.generatePath(), newFileName);
            if (fileService.save(sysFile) > 0) {
                ResultVo resultVo = new ResultVo();
                resultVo.put("fileId", sysFile.getId());
                resultVo.put("fileUrl", sysFile.getFileUrl());
                String FileName = sysFile.getFileName();
                String[] aa = FileName.split("\\\\");
                String name = aa[aa.length - 1];
                resultVo.put("fileName", name);
                resultVo.put("fileSize", sysFile.getFileSize());
                resultVo.put("msg", "上传成功！");
                return resultVo;
            }
        } catch (Exception e) {
            return ResultVo.error();
        }
        return ResultVo.error();
    }

    /**
     * latedit富文本编辑器上传文件
     */
    @ResponseBody
    @PostMapping("/layedit")
    public ResultVo layedit(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        try {
            String contextPath = request.getContextPath();
            String originalFilename = file.getOriginalFilename();
            String oldFileName = originalFilename.substring(originalFilename.lastIndexOf("\\") + 1);
            String newFileName = FileUtils.renameToUuid(oldFileName);
            String fileUrl = "/files/" + FileUtils.generatePath() + newFileName;
            FileDO sysFile = new FileDO(FileType.fileType(oldFileName), fileUrl, oldFileName, file.getSize());
            FileUtils.uploadFile(file.getBytes(), seqbConfig.getUploadPath() + FileUtils.generatePath(), newFileName);
            if (fileService.save(sysFile) > 0) {
                ResultVo resultVo = new ResultVo();
                String FileName = sysFile.getFileName();
                String[] aa = FileName.split("\\\\");
                String name = aa[aa.length - 1];
                Map<String, Object> dataMap = new HashMap<>(16);
                dataMap.put("title", name);
                dataMap.put("src", contextPath + sysFile.getFileUrl());
                dataMap.put("id", sysFile.getId());
                resultVo.put("data", dataMap);
                resultVo.put("msg", "上传成功！");
                return resultVo;
            }
        } catch (Exception e) {
            return ResultVo.error();
        }
        return ResultVo.error();
    }

    /**
     * 下载文件
     */
    @GetMapping("downloadByUrl")
    public void downloadByUrl(String fileName, HttpServletResponse response) {
        String uploadPath = seqbConfig.getUploadPath();
        FileUtils.downloadFile(fileName, uploadPath, response);
    }
}
